<?php

class dbt_userApi extends sing_table
{
    private $_memoryClear = 1;
    private $_G;
    private $_mid;
    private $_openid;
    private $_memberId;
    static $_wxUser; // 存储wxuser数据

    //构造方法
    function __construct()
    {
        global $_G;
        $this->_G = &$_G;
        $this->_mid = $_GET['mid'];
        $this->_openid =  &$_G[$this->_mid]['openid'];
        $this->_memberId = &$_G[$this->_mid]['memberid'];
    }

    public function fetchWxUser($openid)
    {
        if (!self::$_wxUser[$openid]) {
            DB::SetMainDB(DB_MAIN);
            self::$_wxUser[$openid] = DB::fetch_first('select * from %t where mid=%s and openid=%s', array('wx_wxuser', $this->_mid, $openid));
        }
        return self::$_wxUser[$openid];
    }

    public function fMemberId()
    {
        $this->_G[$this->_mid]['memberid'] = $this->_G[$this->_mid]['memberid'] != -1 ? $this->_G[$this->_mid]['memberid'] : C::t('#api#user')->createOpenId($this->_mid, $this->_G[$this->_mid]['openid'], $this->_G['clientip']);
    }

    //用于接收get传的member_id
    public function GetMemberId(){


            $member_id = intval($this->_G['g_member_id']);
            if(!$member_id){
                $member_id = -1;
            }

        return $member_id;
    }


    //API会员验证 初始化memberid  注： 为空时 memberid = -1
    public function ApiInitUser($_mid = '')
    {
        //var_dump(defined('ApiInitUser'));

        if (defined('ApiInitUser')) {
            return false; //防止重复调用
        }
        global $_G;

        if ($_G[$_mid]['openid']) {
            //$_G[$_mid]['memberid'] = C::t('#api#user')->createOpenId($_mid,$_G[$_mid]['openid'],$_G['clientip']);
        }

        if (!$_G[$_mid]['memberid']) {
            if ($_G[$_mid]['openid']) {
                DB::SetMainDB(DB_MAIN);
                $member = DB::fetch_first("select id from %t where display=1 and `openid`=%s and mid=%s", array("common_member", $_G[$_mid]['openid'], $_mid));
                
                $_G[$_mid]['memberid'] = $member['id'] ? $member['id'] : -1;
            } else {
                $_G[$_mid]['memberid'] = -1;
            }
        }

        if ($_G[$_mid]['memberid'] != -1) {
            $member = DB::fetch_first('select `openid`,`unionid` from %t where mid=%s and id=%d', array('common_member', $_mid, $_G[$_mid]['memberid']));
            //初始化会员信息
            $_G[$_mid]['openid'] = $member['openid'];
            $_G[$_mid]['unionid'] = $member['unionid'];
            $_G[$_mid]['member'] = $this->getUserBase($_G[$_mid]['memberid'], $_mid);//会员信息
        }
        define('ApiInitUser', true);
        return 0;
    }

    public function nSign()
    {
        global $_G;

        if($_GET['sw'] == 1){
            echo $this->_openid;
            exit;
        }

        if ((!$_G[$this->_mid]['memberid'] || $_G[$this->_mid]['memberid'] == -1) && !$this->_openid) {
            $clientkey = getcookie('HeaderKey_'. $this->_mid);
            //POst过来的用户信息
            $clientkey = $clientkey ? $clientkey : $_GET['HeaderKey'];
            
            $thisArr = explode("\t", SING_auth($clientkey,'DECODE', md5(getglobal('cookiepre','config/cookie').$_SERVER['HTTP_USER_AGENT']) ));
            list($auType, $openid, $mid, $subscribe) = $thisArr;
            C::t("D")->WriteLogFile("memberId：" . $_G[$this->_mid]['memberid'] . ",HeaderKey：" . $clientkey . ",auType：" . $auType . ",openid：" . $openid.",md5：".SING_auth($clientkey,'DECODE', md5(getglobal('cookiepre','config/cookie').$_SERVER['HTTP_USER_AGENT']) ).' $_SERVER[\'HTTP_USER_AGENT\']:'.$_SERVER['HTTP_USER_AGENT'].",thisArr:". json_encode($thisArr), "nSign.log", "验证登录，时间：");
            C::t('G')->rJson(array('Error' => 301, 'Msg' => '请先登录吧'));
        }
    }

    //店铺登录
    public function Store_nSign()
    {
        global $_G;

        if ($_G[$this->_mid]['memberid'] && $_G[$this->_mid]['memberid'] != -1) {
            $storeId = C::t('#api#storeweb')->getStore($_G[$this->_mid]['memberid']);
            if ($storeId) {
                return $storeId;
            } else {
                C::t('G')->rJson(array('Error' => 302, 'Msg' => '您还没有自己的店铺！'));
            }
        } else {
            C::t('G')->rJson(array('Error' => 301, 'Msg' => '请先登录吧'));
        }

    }


    //门店登录
    public function Outlet_nSign()
    {
        global $_G;
        if ($_G[$this->_mid]['auType'] != 'pc') {
            return 0;
        }
        if ($_G[$this->_mid]['memberid'] && $_G[$this->_mid]['memberid'] != -1) {

        } else {
            C::t('G')->rJson(array('Error' => 301, 'Msg' => '请先登录吧'));
        }

    }

    public function member_all( $where='' )
    {
        DB::SetMainDB(DB_MAIN);
        $member = DB::fetch_all('select * from %t where %i', array('common_member', $where));
        return $member;
    }
    
    public function memberIds2perfec($memberIds=array())
    {
        if(!$memberIds){
            return array();
        }
        DB::SetMainDB(DB_MAIN);
        $data = DB::fetch_all('select id,member_id,name,phone,idcard,vipcode from %t where display=1 and member_id in(%n)', array('common_member_perfect', $memberIds),"member_id");
        return $data;
    }

    public function fetchMemberId($_mid)
    {
        global $_G;

        return $_G[$_mid]['pcmemberid'] ? $_G[$_mid]['pcmemberid'] : -1;
    }

    //创建ios对应开放平台的会员标识 (系统内用的公共方法)
    public function createAppOpenUser($mid = '', $openid = '', $unionid = '')
    {
        if (!$mid || !$openid || !$unionid) {
            echo json_encode(array('Error' => 1, 'Msg' => 'createIosUser参数不正确'));
            exit;
        }
        $appUser = DB::result_first('select id from %t '
            . 'where mid=%s and unionid=%s', array('wx_appuser', $mid, $unionid));
        if (!$appUser) {
            $insert = array();
            $insert['openid'] = $openid;
            $insert['unionid'] = $unionid;
            $insert['inputtime'] = TIME;
            //$insert['country'] = $country;
            //$insert['lang'] = $lang;
            $insert['mid'] = $mid;
            $appUser = DB::insert('wx_appuser', $insert, true);
        }
        return $appUser;
    }

    /*
     *  每次获取信息时更新appuser表的 信息
     */
    public function updateAppUserInfo($unionid = '', $member_id = 0)
    {
        global $_G, $_mid;
        $city = trim($_G['g_city']);
        $country = trim($_G['g_country']);
        $headimgurl = trim($_G['g_headimgurl']);
        $lang = trim($_G['g_language']);
        $nickname = trim($_G['g_nickname']);
        $privilege = is_array($_G['g_privilege']) ? json_encode($_G['g_privilege']) : trim($_G['g_privilege']);
        $province = trim($_G['g_province']);
        $appUser = DB::result_first('select id from %t '
            . 'where mid=%s and unionid=%s', array('wx_appuser', $_mid, $unionid));
        if ($appUser) {
            $update = array();
            $update['updatetime'] = TIME;
            $update['lang'] = $lang;
            $update['country'] = $country;
            $update['city'] = $city;
            $update['headimgurl'] = $headimgurl;
            $update['nickname'] = $nickname;
            $update['privilege'] = $privilege;
            $update['province'] = $province;
            DB::update('wx_appuser', $update, 'id=' . $appUser);//更新会员信息
        }

        /*
         * 和微信关联
         * $openid 是开放平台的
         */
        $commenMember = DB::fetch_first('select `id`,`openid`,`unionid` from %t where id=%d and mid=%s', array('common_member', $member_id, $_mid));
        /*
         * 检查相互关联的账号是否匹配
         */
        if ($commenMember['unionid']) {
            if ($commenMember['unionid'] != $unionid) {
                return array('Error' => 1, 'Msg' => '账号和绑定的微信不匹配');
            }
        }
        if ($commenMember['id'] && !$commenMember['openid']) {
            $wxuseropen = DB::fetch_first('select `openid`,`nickname`,`headimgurl` from %t '
                . 'where mid=%s and unionid=%s', array('wx_wxuser', $_mid, $unionid));//获取wxuser 里的 openid
            $update = array();
            $update['unionid'] = $unionid;
            !$wxuseropen['openid'] ? 0 : $update['openid'] = $wxuseropen['openid'];
            $update['updatetime'] = TIME;
            if (!$update['openid'] && !$update['unionid']) {
                return 0;
            }
            /*----检查头像 Start-如果没有昵称和头像 先设置成微信的昵称和头像----*/
            $register = $this->getActFixCollect($_mid);
            foreach ($register as $k => $v) {
                if ($v['sys'] && $v['ident'] == 'headimg' && !$v['content'] && $wxuseropen['headimgurl']) {//更新头像
                    $info = array();
                    $info['updatetime'] = TIME;
                    $info['content'] = $wxuseropen['headimgurl'];
                    $distributionWhere = $wxuseropen['openid'] ? ' and (openid=\'' . $wxuseropen['openid'] . '\' or member_id=' . $commenMember['id'] . ')' : ' and member_id=' . $commenMember['id'];
                    DB::SetMainDB(DB_MAIN);
                    DB::update('common_act_collect_detail', $info, DB::format('mid=%s and act_id=%d %i', array($this->_mid, $v['id'], $distributionWhere)));
                } else if ($v['sys'] && $v['ident'] == 'nickname' && !$v['content'] && $wxuseropen['nickname']) {//更新昵称
                    $info = array();
                    $info['updatetime'] = TIME;
                    $info['content'] = $wxuseropen['nickname'];
                    $distributionWhere = $wxuseropen['openid'] ? ' and (openid=\'' . $wxuseropen['openid'] . '\' or member_id=' . $commenMember['id'] . ')' : ' and member_id=' . $commenMember['id'];
                    DB::SetMainDB(DB_MAIN);
                    DB::update('common_act_collect_detail', $info, DB::format('mid=%s and act_id=%d %i', array($this->_mid, $v['id'], $distributionWhere)));
                }
            }
            /*--检查头像 End---*/
            DB::update('wx_appuser', array('member_id' => $member_id), array('unionid' => $unionid));
            DB::update('common_member', $update, array('id' => $member_id, 'mid' => $_mid));
        }
    }

    //获取会员基本信息 手机号 头像 昵称 卡号 等不变的信息
    public function getUserBase($id, $mid = '', $_upmemory = 0)
    {
        if (!$mid || !$id) {
            return false;
        }
        $_upmemory = $_upmemory ? $_upmemory : $this->_memoryClear;
        if (!$_upmemory) {
            $r = memory('get', 'wx-api-getUserBase-' . $mid . '-' . $id);
        }
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_first('select `id`,`gid`,`number_other`,`openid`,`nickname`,`headimg` from %t where mid=%s and id=%d', array('common_member', $mid, $id));
            if (!$r) {
                return false;
            }
            $r['groupid'] = $r['gid']; //会员组id

            $register = $this->getActFixCollect($mid, $id);

            $tempregister = array();
            foreach ($register as $k => $v) {
                $tempregister[$v['ident']] = $v['content'];
            }
            $tempregister = $tempregister ? $tempregister : array('headimg' => '', 'nickname' => '');
            $r = array_merge($tempregister, $r);
            //  var_dump($tempregister);
            /*-余额--*/
            $ye = $this->fetchUserBalance($r);
            $r['balance'] = intval($ye['value']);//余额
            $r['do_balance'] = C::t('G')->lastPrice($r['balance']);
            $distributionWhere = $r['openid'] ? ' and (openid=\'' . $r['openid'] . '\' or member_id=' . $id . ')' : ' and member_id=' . $id;
            DB::SetMainDB(DB_ESHOP);
            $distribution = DB::fetch_first('select `id`,`status` from %t where mid=%s and display=1 %i order by id desc', array('es_distribution', $mid, $distributionWhere));
            $r['distributionid'] = intval($distribution['id']); //分销会员id    
            $r['distributionstatus'] = intval($distribution['status']); //分销会员状态 1通过（正式分销会员）

            DB::SetMainDB(DB_ESHOP);
            $distributionStore = DB::fetch_first('select `id`,`status` from %t where mid=%s and display=1 %i order by id desc', array('es_distribution_stores', $mid, $distributionWhere));
            $r['distribution_storeid'] = intval($distributionStore['id']);
            $r['distribution_storestatus'] = intval($distributionStore['status']);

            DB::SetMainDB(DB_ESHOP);
            $r['store'] = DB::fetch_first('select `id` from %t where mid=%s and member_id=%d and display=1', array('es_store', $mid, $id));
            unset($r['openid']);
            memory('set', 'wx-api-getUserBase-' . $mid . '-' . $id, $r);

        }
        return $r;
    }

    /*
     * 获取common_member表信息
     */
    public function fetchCommonMember($member_id)
    {
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select `id`,`gid`,`number_other`,`openid`,`nickname`,`comcode` from %t where mid=%s and id=%d', array('common_member', $this->_mid, $member_id));
        return $r;
    }

    /*
     * 获取会员余额
     * $commonMember = 会员member表基本信息  通过 fetchCommonMember 方法获得
     */
    public function fetchUserBalance($commonMember = array())
    {
        return array();
        DB::SetMainDB(DB_MAIN);
        $memberBalance = DB::fetch_first('select `value` from %t where mid=%s and member_id=%d and display=1', array('common_member_balance', $this->_mid, $commonMember['id']));

        //兼容旧版本  同时记录两种余额方便 分别做减法 wxuser会优先减去
        $memberBalance['member_value'] = $memberBalance['value'];
        $memberBalance['wxuser_value'] = 0;

        if ($commonMember['openid']) {
            $this->fetchWxUser($commonMember['openid']);
            DB::SetMainDB(DB_MAIN);
            $memberBalance['value'] += self::$_wxUser[$commonMember['openid']]['ye'];
            $memberBalance['wxuser_value'] += self::$_wxUser[$commonMember['openid']]['ye'];

        }
        return $memberBalance;
    }

    /*
     * 获取会员所属组信息
     * 组不存在时 默认组折扣=1  既没有折扣
     * $commonMember = 会员member表基本信息  通过 fetchCommonMember 方法获得
     */
    public function fetchUserGroup($commonMember = array())
    {

        $groupId = 0;
        $group = array();
        /*
         * 新版common_member 暂未加入 会员组 2016年8月3日 16:02:18
         */

        //兼容旧版本
        if ($commonMember['openid']) {
            $this->fetchWxUser($commonMember['openid']);
            $groupId = self::$_wxUser[$commonMember['openid']]['groupid'];
        }

        if ($groupId) {
            $group = $this->getGroupM($this->_mid, $groupId);
            $group['discounts'] = floatval($group['discounts']);
            $group['discounts'] = ($group['discounts'] > 1 || $group['discounts'] <= 0) ? 1 : $group['discounts'];//组折扣
        } else {
            $group['id'] = $commonMember['gid'];
            $group['discounts'] = 1; //组折扣
        }
        return $group;
    }

    /*
     * 获取家庭会员信息
     */
    public function familyUser($member_id)
    {
        $familyUser = DB::fetch_first('select * from %t where display=1 and mid=%s and member_id=%d', array('common_member_perfect', $this->_mid, $member_id));
        return $familyUser;
    }

    /*
     * 获取会员所持有积分信息
     *
     * $commonMember = 会员member表基本信息  通过 fetchCommonMember 方法获得
     *
     * 由于新版会员和老版会员共用同一个积分表 所以这里保证不会出现重复数据
     *
     *
     */
    public function fetchUserIntegral($commonMember)
    {

        if ($commonMember['openid']) {
            $wxR = DB::fetch_first('select * from %t where mid=%s and openid=%s  and display=1 order by id asc', array('wx_integral', $this->_mid, $commonMember['openid']));
            if ($wxR['id']) {

                if (!$wxR['member_id']) {

                    //互相兼容
                    $mR = DB::fetch_first('select * from %t where mid=%s and member_id=%d and display=1', array('wx_integral', $this->_mid, $commonMember['id']));
                    /*
                     * 如果member_id没有单一的数据则
                     * 自动更新member_id到 积分表
                     * 第一次同步member_id 和 openid 0.0 又向整合会员迈出了一步 !`~`~! 2016年8月12日 19:37:41
                     */
                    if (!$mR['id']) {
                        DB::update('wx_integral', array('member_id' => $commonMember['id']), DB::format('mid=%s and id=%d', array($this->_mid, $wxR['id'])));
                        $wxR['member_id'] = $commonMember['id'];
                    } else {

                        $update = array();
                        //反之加上积分
                        for ($i = 1; $i <= 8; $i++) {
                            $mR['value' . $i] += $wxR['value' . $i];
                            $update['value' . $i] = $mR['value' . $i];
                        }
                        $update['openid'] = $commonMember['openid'];
                        //更新member积分并删除原有老积分 由于是系统自动操作 标记 -2 以防万一
                        DB::update('wx_integral', $update, DB::format('mid=%s and id=%d', array($this->_mid, $wxR['id'])));
                        DB::update('wx_integral', array('display' => -2), DB::format('mid=%s and id=%d', array($this->_mid, $wxR['id'])));

                        //合并完成返回新数据
                        $wxR = $wxR;
                    }

                }
            }
        } else {
            //没有
            $wxR = DB::fetch_first('select * from %t where mid=%s and member_id=%d  and display=1', array('wx_integral', $this->_mid, $commonMember['id']));
            if (!$wxR) {
                $insert = array();
                $insert['value1'] = $insert['value2'] = $insert['value3'] = $insert['value4'] = $insert['value5'] = $insert['value6'] = $insert['value7'] = $insert['value8'] = 0;
                $insert['mid'] = $this->_mid;
                $insert['openid'] = $commonMember['openid'];
                $insert['member_id'] = $commonMember['id'];
                $insert['inputtime'] = TIME;
                $insert['id'] = DB::insert('wx_integral', $insert, true);
                $wxR = $insert;
            }
        }

        return $wxR;
    }

    public function getAddressSet($uid = 0, $_uid = 0)
    {
        //if(!$_mid || !$_openid) return array();
        //DB::SetMainDB(3);
        //$r = DB::fetch_first('select is_name,is_phone,is_tel,is_zipcode,is_country,is_province,is_city,is_district,is_area,is_address,is_set_default,is_best_time,id as aid from %t where display=1 and status=1 and mid=%s', array('common_address_setting', $this->_mid));

        if (!$r) {
            $insert = array();
            $insert['mid'] = $this->_mid;
            $insert['uid'] = $uid;
            $insert['_uid'] = $_uid;
            $insert['inputtime'] = TIME;
            $insert['status'] = 1;
            $insert['display'] = 1;
            $insert['is_name'] = 2;
            $insert['is_phone'] = 2;
            $insert['is_tel'] = 1;
            $insert['is_zipcode'] = 1;
            $insert['is_country'] = 2;
            $insert['is_province'] = 2;
            $insert['is_city'] = 2;
            $insert['is_district'] = 2;
            $insert['is_area'] = 2;
            $insert['is_address'] = 2;
            $insert['is_set_default'] = 1;
            $insert['is_best_time'] = 1;
            //$insert['aid']=DB::insert('common_address_setting',$insert,true);
            $r = $insert;
        }

        return $r;
    }

    /*
     * 获取会员可编辑的信息字段 程序内使用没有过滤列表
     */
    public function getActFixCollect($mid, $member_id = 0)
    {
        if (!$mid) {
            return false;
        }
        global $_G;
        if ($member_id && $member_id != -1) {
            $memberid = $member_id;
        } else {
            $memberid = $_G[$mid]['memberid'] ? $_G[$mid]['memberid'] : -1;
            $openid = $_G[$mid]['openid'];
        }
        if ($memberid == -1) {
            return array();
        }
        //读取会员设置
        $settingId = $this->getMemberSettingId($mid);
        //  echo var_dump($settingId);
        $distributionWhere = $openid ? ' and (openid=\'' . $openid . '\' or member_id=' . $memberid . ')' : ' and member_id=' . $memberid;
        //读取注册设置
        //DB::SetMainDB(DB_MAIN);
        //$register = DB::fetch_all('select `id`,`type`,`ident`,`title`,`is_required`,`sys` from %t '
//            . 'where mid=%s and tablename=%s and tableid=%d and ((is_using=1 and is_show=1) or sys=1) and status=1 and display=1 order by turn desc', array('common_act', $mid, 'common_member_setting', $settingId));
        $register = array();

        $actCollectCount = DB::result_first('select id from %t where mid=%s and tablename=%s and display=1 %i', array('common_act_collect', $mid, 'common_member', $distributionWhere));
        if (!$actCollectCount) {
            $sql_act['tablename'] = 'common_member';
            $sql_act['tableid'] = $memberid;
            $sql_act['clientip'] = $_G['clientip'];
            //$sql_act['_uid']         = $this->_G['_uid'];
            $sql_act['mid'] = $mid;
            $sql_act['openid'] = $openid;
            $sql_act['member_id'] = $memberid;
            $sql_act['inputtime'] = TIME;
            $sql_act['status'] = 1;
            $sql_act['display'] = 1;
            DB::SetMainDB(DB_MAIN);
            $collect_id = DB::insert('common_act_collect', $sql_act, true);
        }
        $data = array();
        $sysHeadimg = 'headimg';
        $sysNickname = 'nickname';
        foreach ($register as $v) {
            if ($v['ident'] == 'nickname') {
                $sysNickname = '';
            }
            if ($v['ident'] == 'headimg') {
                $sysHeadimg = '';
            }
//            $temp = array();
//            $temp['act_id'] =  $v['id'];
//            $temp['ident'] = $v['ident'];
//            $temp['title'] = $v['title'];
//            $temp['is_required'] = $v['is_required'];
            $collectDetail = DB::fetch_first('select `id`,`content` from %t where mid=%s and display=1 and act_id=%d %i', array('common_act_collect_detail', $mid, $v['id'], $distributionWhere));
            if (!$collectDetail['id']) {
                //$collectDetail['content'] = '';
                //如果没有昵称 默认等于微信昵称或者手机号 或者账号
                $collectDetail['content'] = $this->fetchNicknameAHeadimg($mid, $member_id, $v['ident'], $collectDetail['content']);

                $sql_insert = array();
                $sql_insert['collect_id'] = $collect_id;
                $sql_insert['act_id'] = $v['id'];
                $sql_insert['ext_id'] = 0;
                $sql_insert['content'] = $collectDetail['content'];
                $sql_insert['tablename'] = 'common_member_setting';
                $sql_insert['tableid'] = $settingId;
                $sql_insert['clientip'] = $_G['clientip'];
                //$sql_insert['_uid']            = $this->_G['_uid'];
                $sql_insert['mid'] = $mid;
                $sql_insert['openid'] = $openid;
                $sql_insert['member_id'] = $memberid;
                $sql_insert['inputtime'] = TIME;
                $sql_insert['status'] = 1;
                $sql_insert['display'] = 1;
                DB::insert('common_act_collect_detail', $sql_insert, true);
            } else {
                $collectDetail['content'] = $this->fetchNicknameAHeadimg($mid, $member_id, $v['ident'], $collectDetail['content']);
            }
            $v['content'] = $collectDetail['content'];
            foreach ($v ? $v : array() as $tk => $tv) {
                if (!$tv) {
                    $v[$tk] = is_numeric($tv) ? 0 : '';
                }
            }
            $data[] = $v;
        }


        if ($sysNickname) {//更新昵称
            $array = array(
                'ident' => $sysNickname,
                'content' => $this->fetchNicknameAHeadimg($mid, $member_id, $sysNickname)
            );
            array_push($data, $array);
        }
        if ($sysHeadimg) {//更新头像
            $array = array(
                'ident' => $sysHeadimg,
                'content' => $this->fetchNicknameAHeadimg($mid, $member_id, $sysHeadimg)
            );
            array_push($data, $array);
        }


        return $data;
    }


    private function fetchNicknameAHeadimg($mid, $memberid, $ident, $content = '')
    {
        //如果没有昵称 默认等于微信昵称或者手机号 或者账号
        if ($ident == 'nickname') {
            $commenMember = DB::fetch_first('select `account`,`number_other`,`openid`,`nickname`,`headimg` from %t where mid=%s and id=%d', array('common_member', $mid, $memberid));
            if ($commenMember['openid']) {
                $content = DB::result_first('select `nickname` from %t where openid=%s', array('wx_wxuser', $commenMember['openid']));
                if (!$commenMember['nickname']) {
                    $mUp = array();
                    $mUp['nickname'] = $content;
                    DB::update('common_member', $mUp, DB::format('mid=%s and id=%d', array($mid, $memberid)));
                }
            } elseif ($commenMember['account']) {
                $content = $commenMember['account'];
            } elseif ($commenMember['number_other']) {
                $content = $commenMember['number_other'];
            }
        }
        if ($ident == 'headimg') {
            $commenMember = DB::fetch_first('select `account`,`number_other`,`openid` from %t where mid=%s and id=%d', array('common_member', $mid, $memberid));
            /*if($commenMember['account']){

            }elseif($commenMember['number_other']){

            }elseif($commenMember['openid']){*/
            $content = DB::result_first('select `headimgurl` from %t where openid=%s', array('wx_wxuser', $commenMember['openid']));
            if (!$commenMember['headimg']) {
                $mUp = array();
                $mUp['headimg'] = $content;
                DB::update('common_member', $mUp, DB::format('mid=%s and id=%d', array($mid, $memberid)));
            }
            /*}*/
        }
        return $content;
    }

    /******************************
     * 验证member_id 是否存在
     *由于 要确定member_id不存在 需要两种值  0 -1 都表示不存在 所有特加一个方法
     *
     */
    public function vMemberId($member_id = 0)
    {
        $m = $member_id ? $member_id : $this->_memberId;
        if ($m == -1 || !$m) {
            return false;
        } else {
            return true;
        }
    }


    /******************************
     * 读取自己的单条收货地址
     * $_id 地址id
     *
     */
    public function getSelfAddressM($_id = 0)
    {

//        if(!$this->_openid && !$this->vMemberId()){
//            return array();
//        }
        $memberWhere = C::t("#api#user")->memberWhere($this->_openid, $this->_memberId);
        if ($_id) {
            $where .= DB::format(' and id=%d ', array($_id));
        }
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select * from %t where display=1 and set_default=1 and mid=%s %i %i', array('common_address', $this->_mid, $where, $memberWhere));
        if ($r) {
            $r['dis'] = '';
            if ($r['dis_id']) {
                DB::SetMainDB(DB_ESHOP);
                $r['dis'] = DB::result_first('select `dis` from %t where mid=%s and id=%d', array('es_outlet_send_range_relation', $this->_mid, $r['dis_id']));
            }
            if($r['ring']){
                $ringD = $this->getExtRegion($r['ring']);
                if(!$ringD){
                    $upd = array();
                    $upd['ring'] = 0;
                    $this->updateAddess($upd['ring'],DB::format("id=%d", array($r['id'])));
                    $r['ring'] = 0;
                }
            }
        }
        return $r;
    }


    public function getMemberSettingId($mid, $upmemory = 0)
    {
        return false;
        if (!$mid) {
            return false;
        }
        $_upmemory = $_upmemory ? $_upmemory : $this->_memoryClear;
        if (!$upmemory) {
            $settingId = memory('get', 'wx-getMemberSettingId-' . $mid);
        }
        if (!$settingId) {
            DB::SetMainDB(DB_MAIN);
            $settingId = DB::result_first('select id from %t '
                . 'where mid=%s and status=1 and display=1', array('common_member_setting', $mid));
            if ($settingId) {
                memory('set', 'wx-getMemberSettingId-' . $mid, $settingId);
            }
        }
        return $settingId;
    }

    //根据unionid 获取会员信息 程序内使用
    public function unionUserInfo($unionid = '', $mid = '')
    {
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select `id`,`openid`,`unionid`,`number_other` from %t where mid=%s and unionid=%s', array('common_member', $mid, $unionid));
        return $r;
    }


    public function get($id, $mid = '', $flag = 0)
    {
        // $r = memory('get' , $openid.'-usr-'.$mid);
        // if(!$r){
        if ($flag) {
            $r = DB::fetch_first('select * from %t where openid=%d and mid=%s limit 1', array('wx_wxuser', $id, $mid));
        } else {
            $r = DB::fetch_first('select * from %t where member_id=%d and mid=%s limit 1', array('wx_appuser', $id, $mid));
        }
        //     memory('set' , $openid.'-usr-'.$mid ,$r);
        // }
        return $r;
    }

    public function getGroupM($mid, $id, $upmemory = 0)
    {
        if (!$mid || !$id) return false;
        if (!$upmemory) $r = memory('get', 'wx-group-' . $mid . '-' . $id);
        if (!$r) {
            DB::SetMainDB(DB_MAIN_READ);
            $r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('wx_group', $mid, $id));
            if ($r) memory('set', 'wx-group-' . $mid . '-' . $id, $r);
        }
        return $r;
    }

    public function getMemberPerfect($memberId, $upmemory = 0)
    {
        if (!$this->_mid || !$memberId) return false;
        if (!$upmemory && !$this->_memoryClear) $r = autoMemory('get', 'wx-getMemberPerfect-' . $this->_mid . '-' . $memberId);
        if (!$r) {
            DB::SetMainDB(DB_MAIN_READ);
            $r = DB::fetch_first('select * from %t where mid=%s and member_id=%d and display > 0', array('common_member_perfect', $this->_mid, $memberId));
            if ($r) autoMemory('set', 'wx-getMemberPerfect-' . $this->_mid . '-' . $memberId, $r);
        }
        return $r;

    }

    //获取收货地址基本信息
    public function getApiAddressBase($mid, $id, $_upmemory = 0)
    {
        $_upmemory = $_upmemory ? $_upmemory : $this->_memoryClear;
        if (!$_upmemory) {
            $r = memory('get', 'wx-getApiAddressBase-' . $mid . '-' . $id);
        }
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_first('select id, name, phone,country,province,city,district, area, address, zipcode, set_default, best_time from %t where mid=%s and id=%d', array('common_address', $mid, $id));
            if ($r) {
                foreach ($r as $k => $v) {
                    switch ($k) {
                        case 'country':
                        case 'province':
                        case 'city':
                        case 'district':
                            $temp = $this->getRegionBase($v);
                            $r['do_' . $k] = $temp['title'];
                            break;
                    }
                }
                memory('set', 'wx-getApiAddressBase-' . $mid . '-' . $id, $r);
            }
        }
        return $r;
    }
    
    public function isRing($district){
        DB::SetMainDB(DB_MAIN);
        $thisCount = DB::result_first('select count(*) from %t where display=1 and parentid=%d', array('common_region_ext', $district));
        return $thisCount;
    }

    //地区列表
    public function getRegionBase($id, $_upmemory = 0)
    {
        $_upmemory = $_upmemory ? $_upmemory : $this->_memoryClear;
        if (!$_upmemory) {
            $r = memory('get', 'wx-getRegionBase-' . $id);
        }
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_first('select id,parentid,title,grade from %t where id=%d', array('common_region', $id));
            if ($r) {
                memory('set', 'wx-getRegionBase-' . $id, $r);
            }
        }
        return $r;
    }
    
    //获取四级地址信息
    public function getExtRegion($_id){
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select * from %t where display=1 and id=%d', array('common_region_ext', $_id));
        return  $r;
    }
    
    //修改收货地址信息
    public function updateAddess($data=array(),$where=""){
        if(!$data || is_array($data) || !$where){
            return false;
        }
        $data['updatetime'] = TIME;
        DB::SetMainDB(DB_MAIN);
        $num = DB::update("common_address", $data, $where);
        return $num;
    }

    //读取单条收货地址
    public function getAddressM($_mid, $_id, $_upmemory = 0)
    {
        $_upmemory = $_upmemory ? $_upmemory : $this->_memoryClear;
        if (!$_upmemory) {
            $r = memory('get', 'wx-getAddressM-' . $_mid . '-' . $_id);
        }
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_first('select `id`,`status`,`display`,`name`,`phone`,`tel`,`zipcode`,`country`,`province`,`city`,`district`,`ring`,`area`,`address`,`set_default`,`best_time` from %t '
                . 'where mid=%s and id=%d', array('common_address', $_mid, $_id));
            if (!$r) {
                DB::SetMainDB(DB_MAIN);
                $r = DB::fetch_first('select `id`,`status`,`display`,`name`,`phone`,`tel`,`zipcode`,`country`,`province`,`city`,`district`,`ring`,`area`,`address`,`set_default`,`best_time` from %t '
                    . 'where mid=%s and status=1 and display=1 order by set_default desc', array('common_address', $_mid));
            }
            if ($r) {
                if($r['ring']){
                    $ringD = $this->getExtRegion($r['ring']);
                    if(!$ringD){
                        $upd = array();
                        $upd['ring'] = 0;
                        $this->updateAddess($upd['ring'],DB::format("id=%d", array($r['id'])));
                        $r['ring'] = 0;
                    }
                }
                foreach ($r as $k => $v) {
                    switch ($k) {
                        case 'country':
                        case 'province':
                        case 'city':
                        case 'district':
                            $temp = $this->getRegionBase($v);
                            $r['do_' . $k] = $temp['title'];
                            break;
                    }
                }
                memory('set', 'wx-getAddressM-' . $_mid . '-' . $_id, $r);
            }
        }
        return $r;
    }


    /*
     * 由于参数是错的 认为没有使用过 直接重写了 2016年8月3日 16:34:01
     */
    public function getIntegralM($oepnid = '', $memberid = 0)
    {
        $oepnid = $oepnid ? $oepnid : $this->_openid;
        $memberid = $memberid ? $memberid : $this->_memberId;
        //global $_G;
        //$distributeWhere = $_G[$mid]['openid']?' and openid=\''.$_G[$mid]['openid'].'\'':' and member_id='.$_G[$mid]['memberid'];
        $distributeWhere = $oepnid ? ' and openid=\'' . $oepnid . '\'' : ' and member_id=' . $memberid;
        $r = DB::fetch_first('select * from %t where mid=%s and openid=%s', array('wx_integral', $this->_mid, $distributeWhere));
        if (!$r) {
            $insert = array();
            $insert['mid'] = $this->_mid;
            $insert['openid'] = $oepnid;
            $insert['member_id'] = $memberid;
            $insert['id'] = DB::insert('wx_integral', $insert, true);
            $r = $insert;
        }
        return $r;
    }


    public function getIntegralSettingM($upmemory = 0)
    {
        if (!$this->_mid) return array();
        if (!$upmemory) $r = memory('get', 'wx-integral_setting-' . $this->_mid);
        if (!$r) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_first('select * from %t where mid=%s', array('wx_integral_setting', $this->_mid));
            if ($r) memory('set', 'es-integral_setting-' . $this->_mid, $r);
        }
        return $r;
    }


    //收货地址注释
    public function getAddressList($_mid = '', $_openid = '', $_memberId = 0)
    {
        $_mid = $_mid ? $_mid : $this->_mid;

        $_openid = $_openid ? $_openid : $this->_openid;
        $_memberId = $_memberId ? $_memberId : $this->_memberId;
        $r = array();
        if ($_openid) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_all('select * from %t where mid=%s and openid=%s and status=1 and display=1 order by set_default desc', array('common_address', $_mid, $_openid));
        } elseif ($_memberId != -1 && $_memberId) {
            DB::SetMainDB(DB_MAIN);
            $r = DB::fetch_all('select * from %t where mid=%s and member_id=%d and status=1 and display=1 order by set_default desc', array('common_address', $_mid, $_memberId));
        }


        return $r;
    }


    //读取运费模版信息
    public function getFreightM($_mid, $_id)
    {
        //if(!$_mid || !$_openid) return array();
        DB::SetMainDB(DB_ESHOP);
        $r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('es_freight', $_mid, $_id));
        return $r;
    }

    //读取运费模版信息
    public function getFreightSetDefault($_mid)
    {
        //if(!$_mid || !$_openid) return array();
        DB::SetMainDB(DB_ESHOP);
        $r = DB::fetch_first('select * from %t where mid=%s and display=1 and status=1 order by set_default desc', array('es_freight', $_mid));
        return $r;
    }

    //读取快递信息
    public function getExpressM($_mid, $_id)
    {
        //if(!$_mid || !$_openid) return array();
        DB::SetMainDB(DB_ESHOP);
        $r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('es_express', $_mid, $_id));
        return $r;
    }

    //读取配送信息
    public function getshippingM($_mid, $_id)
    {
        //if(!$_mid || !$_openid) return array();
        DB::SetMainDB(DB_ESHOP);
        $r = DB::fetch_first('select * from %t where mid=%s and id=%d', array('es_shipping', $_mid, $_id));
        return $r;
    }

    //地区列表
    public function getRegionM($_mid, $_id)
    {
        //if(!$_mid || !$_openid) return array();
        //DB::SetMainDB(3);
        DB::SetMainDB(DB_MAIN);
        $r = DB::fetch_first('select * from %t where id=%d', array('common_region', $_id));
        return $r;
    }

    //订单状态数量
    public function getOrderCount($_mid, $_openid, $type = 'waitPay')
    {
        //if(!$_mid || !$_openid) return array();
        switch ($type) {
            //待付款订单
            case 'waitingPay':
                $where = 'and order_status=0 and pay_status=0 and pay_type=1';
                break;
            //待发货订单
            case 'waitingSend':
                $where = 'and order_status=0 and send_status=0 and ((pay_status=1 and pay_type=1) or pay_type=2)';
                break;
            //待收货订单
            case 'waitingTake':
                $where = 'and order_status=0 and send_status=1 and ((pay_status=1 and pay_type=1) or pay_type=2)';
                break;
            //已完成订单
            case 'success':
                $where = 'and order_status=1';
                break;
        }
        DB::SetMainDB(DB_ESHOP);
        $r = DB::result_first('select count(*) from %t where mid=%s and openid=%s %i', array('es_order', $_mid, $_openid, $where));
        return $r;
    }

    //获取商品信息
    public function getGoodsM($mid, $id)
    {
        if (!$mid || !$id) return false;

        DB::SetMainDB(DB_ESHOP);
        $r = DB::fetch_first('select * from %t where mid=%s and id=%d and status=1 and display=1', array('es_goods', $mid, $id));

        return $r;
    }

    //获取商品信息
    public function getStoreM($mid, $id)
    {
        if (!$mid || !$id) return false;

        DB::SetMainDB(DB_ESHOP);
        $r = DB::fetch_first('select * from %t where mid=%s and id=%d and status=1 and display=1', array('es_store', $mid, $id));

        return $r;
    }

    //商品优惠券
    public function getDiscountvoucherM($_mid, $_id, $_upmemory = 1)
    {
        if (!$_mid || !$_id) return false;
        if (!$_upmemory) $r = memory('get', 'es-discountvoucher-' . $_mid . '-' . $_id);
        if (!$r) {
            DB::SetMainDB(DB_ESHOP);
            $r = DB::fetch_first('select * from %t where mid=%s and id=%d and display=1', array('es_coupon', $_mid, $_id));
            if ($r) memory('set', 'es-discountvoucher-' . $_mid . '-' . $_id, $r);
        }
        return $r;
    }


    //优惠券信息 记录的
    public function getDiscountvoucherLogList($mid = '', $where_member = '', $id = 0)
    {
        if (!$mid || !$where_member) return false;
        $where = '';
        if ($id) {
            $where = ' and coupon_id = ' . intval($id);
        }
        DB::SetMainDB(DB_ESHOP);
        $r = DB::fetch_all('select * from %t where mid=%s and display=1 %i %i ', array('es_coupon_log', $mid, $where, $where_member));
        return $r;
    }

}